#!/usr/bin/python
# -*- coding: utf-8 -*-

#import sip
#sip.setapi('QVariant', 2)

from PyQt4 import QtCore, QtGui, QtSql, uic
import sys
from tclasses import *

__version__ = "1.0"

app = QtGui.QApplication(sys.argv)
form_class, base_class = uic.loadUiType('untitled.ui')

## за кирилицата; после всичко се конвертира с unicode(string, 'cp1251') - native python function
QtCore.QTextCodec.setCodecForLocale(QtCore.QTextCodec.codecForName("cp1251"))
QtCore.QTextCodec.setCodecForCStrings(QtCore.QTextCodec.codecForName("cp1251"))
QtCore.QTextCodec.setCodecForTr(QtCore.QTextCodec.codecForName("cp1251"))

def toCp1251(string):
    return unicode(string, 'cp1251')

## autoComplete client name and family name
class DictionaryCompleter(QtGui.QCompleter):
    def __init__(self, parent=None, aList=None):
        QtGui.QCompleter.__init__(self, aList, parent)

## main window class
class DemoImpl(QtGui.QMainWindow, form_class):
    
    def __init__(self, *args):
        super(DemoImpl, self).__init__(*args)
        self.setupUi(self)
        
        ## set completer for names
        self.compl = DictionaryCompleter(None, clientsList)
        self.lineEditSenderName.setCompleter(self.compl)
        self.lineEditReceiverName.setCompleter(self.compl)

        ## set validators for numeric fields
        self.lineEditPackWeght.setValidator(QtGui.QDoubleValidator(self))
        self.lineEditPackCount.setValidator(QtGui.QDoubleValidator(self))
        self.lineEditNalojenPlatejValue.setValidator(QtGui.QDoubleValidator(self))
        self.lineEditFixedTimeFee.setValidator(QtGui.QDoubleValidator(self))
        self.lineEditInsuranceValue.setValidator(QtGui.QDoubleValidator(self))
        
        self.init()

    def init(self):
        self.lineEditOrderNomer.clear()
        self.lineEditOpakowka.clear()
        self.lineEditPackDesciption.clear()
        ## clear sender data
        self.lineEditSenderName.clear()
        self.lineEditSenderAddress.clear()
        self.lineEditSenderPhone.clear()
        self.lineEditSenderTown.clear()
        self.sender = None
        ## clear receiver data
        self.lineEditReceiverName.clear()
        self.lineEditReceiverAddress.clear()
        self.lineEditReceiverPhone.clear()
        self.lineEditReceiverTown.clear()
        self.receiver = None
        ## set default checks for check buttons
        self.radioButtonSender.setChecked(True)
        self.atAccountOf = 'sender'
        self.radioButtonPoSmetka.setChecked(True)
        self.paymentType = 'account'
        ## clear checks
        self.checkBoxBackDocs.setCheckState(QtCore.Qt.Unchecked)
        self.checkBoxBackRasp.setCheckState(QtCore.Qt.Unchecked)
        self.checkBoxOnDemand.setCheckState(QtCore.Qt.Unchecked)
        self.checkBoxFixedTime.setCheckState(QtCore.Qt.Unchecked)
        self.checkBoxInsurance.setCheckState(QtCore.Qt.Unchecked)
        ## init time lineEdit
        self.setTimee()
        ## init serviceSpeed button
        self.speed = bz.getServiceSpeed()
        self.currentSpeedIndex = 0
        self.pushButtonServiceSpeed.setText(self.speed[self.currentSpeedIndex])
        ## init destination town
        self.destination = 'sofia'
        ## init financial part
        self.initFinancials()
        ## QDocument for printing tovs
        self.tovPrintDocument = None
        ## date
        self.dateEdit.setDate(QtCore.QDate.currentDate())
        ## set next order nomer
        self.initClients()
        self.tovWithModel()
        
    
    #----------------------------------------------------------------------
    def initMapper(self):
        """"""
        model = QtSql.QSqlTableModel(self)
        model.setTable("klienti")
        model.setSort(0, QtCore.Qt.AscendingOrder)
        model.select()
        
        self.mapper = QtGui.QDataWidgetMapper(self)
        self.mapper.setSubmitPolicy(QtGui.QDataWidgetMapper.ManualSubmit)
        self.mapper.setModel(model)
        self.mapper.addMapping(self.lineEditSenderName, 0)
        self.mapper.addMapping(self.lineEditSenderAddress, 1)
        self.mapper.addMapping(self.lineEditSenderPhone, 4)
        self.mapper.addMapping(self.lineEditSenderTown, 5)
        self.mapper.toLast()
        
    def initFinancials(self):
        ## clear gui
        self.lineEditPackWeght.clear()
        self.lineEditPackCount.clear()
        self.lineEditNalojenPlatejValue.clear()
        self.lineEditNalojenPlatejFee.clear()
        self.lineEditFixedTimeFee.clear()
        self.lineEditCourierFee.clear()
        self.lineEditCourierFeeInclVat.clear()
        self.lineEditTotal.clear()
        ## init financial values
        self.packWeight = 0.5
        self.packCount = 0.0
        self.nalojenPlatejValue = 0.0
        self.courierFee = 0.0
        self.fixedTimeFee = 0.0
        self.insuranceValue = 0.0
        self.obrDocsFee = 0.0
        self.obrRazpiskaFee = 0.0
        self.onDemandFee = 0.0

    def setTimee(self):
        date = QtCore.QDateTime.currentDateTime()
       # self.lineEditDate.setText(date.toString('d MMMM yyyy'))
        self.lineEditTime.setText(date.toString('hh:mm:ss'))
    
###################################### Tovs TAB ##################################################################
        
    #def initListWidgetTovs(self):
        #tovs = bz.getTovs()
        #self.lastOrderNomer = tovs[-1].orderNomer
        #self.lineEditOrderNomer.setText(toCp1251(str(int(self.lastOrderNomer)+1)))
        
        #tovHeaders = ["orderNomer", "tovDate", "tovTime", "opakowka", "serviceSpeed",\
                    #"atAccountOF", "paymentType", "obrDocs", "obrRazpiska", "onDemand",\
                    #"packDescription", "fromOffice", "toOffice", "senderName", "senderStreet",\
                    #"senderPhone", "receiverName", "receiverStreet", "receiverPhone", "packCount",\
                    #"packWeight", "nalojenPlatej", "feeNalPlatej", "fixedTimeFeeQ", "courierFee",\
                    #"courierFeeInclVAT", "total"]
        
        #def addTov(model, tov):
            #tovDict = tov.getDataAsDict()
            #model.insertRow(0)
            #for col, name in enumerate(tovHeaders):
                #model.setData(model.index(0, col), tovDict[name])
           
        ##@QtCore.pyqtSignature("QStandardItem")
        #def msg(s):
            #print 'item changed', s.data(QtCore.Qt.DisplayRole).toString()
            
        #model = QtGui.QStandardItemModel(0, len(tovHeaders))
        
        #for num, tovHeader in enumerate(tovHeaders):
            #model.setHeaderData(num, QtCore.Qt.Horizontal, tovHeader)        
        
        #for tov in tovs:
            #addTov(model, tov)
       
        #self.treeViewTovs.setModel(model)
       
        #self.connect(model, QtCore.SIGNAL('itemChanged (QStandardItem *)'), msg)
        
    def createTov(self):
        backDocs = self.checkBoxBackDocs.isChecked()
        backRazp = self.checkBoxBackRasp.isChecked()
        onDemand = self.checkBoxOnDemand.isChecked()
        fixTime, ok = self.lineEditFixedTimeFee.text().toFloat()
        if ok:
            ft = fixTime
        else:
            ft = self.fixedTimeFee
        
        currentTov = Tov(self.lineEditOrderNomer.text(), self.lineEditDate.text(), self.lineEditTime.text(), \
                        self.lineEditOpakowka.text(), self.pushButtonServiceSpeed.text(), self.atAccountOf, \
                        self.paymentType, backDocs, backRazp, onDemand, self.lineEditPackDesciption.text(), \
                        self.lineEditSenderTown.text(), self.lineEditReceiverTown.text(),\
                        self.lineEditSenderName.text(), self.lineEditSenderAddress.text(), self.lineEditSenderPhone.text(),\
                        self.lineEditReceiverName.text(), self.lineEditReceiverAddress.text(), self.lineEditReceiverPhone.text(),\
                        self.lineEditPackCount.text(), self.lineEditPackWeght.text(), self.lineEditNalojenPlatejValue.text(), \
                        self.lineEditNalojenPlatejFee.text(), ft, self.lineEditCourierFee.text(), \
                        self.lineEditCourierFeeInclVat.text(), self.lineEditTotal.text())
        if currentTov:
            return currentTov
        else:
            return None  
        
    
    ## @QtCore.pyqtSignature("QModelIndex&")
    
    #----------------------------------------------------------------------
    def tovWithModel(self):
        """populate tovs' list, using model/view approach"""
        tovs = bz.getTovs()
        self.lastOrderNomer = tovs[-1].orderNomer
        self.lineEditOrderNomer.setText(toCp1251(str(int(self.lastOrderNomer)+1)))
        
        
        model = QtSql.QSqlTableModel(self)
        model.setTable("tov")
        model.setSort(0, QtCore.Qt.AscendingOrder)
        model.select()
        
        
        self.tableView.setModel(model)
        print model.primaryKey().name()
        
        
    def on_tableView_clicked(self):
        
        for x in self.tableView.selectedIndexes():
            print toCp1251(x.data().toString())
            
      #  self.tovPrintDocument = TovPlainDoc()
      #  self.textEditTovDisplay.setDocument(tovdispl)
        
    #----------------------------------------------------------------------
    
       
    ########################## CLIENTS' TAB ##########################################    
        
    def initClients(self):
        """ set model and mapper for the field in clients' tab"""
        
        model = QtSql.QSqlRelationalTableModel(self)
        model.setTable("klienti")
        model.setRelation(0, QtSql.QSqlRelation("Address", "clientID", "street"))
        model.setSort(0, QtCore.Qt.AscendingOrder)
        model.select()
        
        self.mapper = QtGui.QDataWidgetMapper(self)
        self.mapper.setSubmitPolicy(QtGui.QDataWidgetMapper.ManualSubmit)
        self.mapper.setModel(model)
        self.mapper.setItemDelegate(QtSql.QSqlRelationalDelegate(self))
        self.mapper.addMapping(self.lineEditName, 1)
        self.mapper.addMapping(self.lineEditSurname, 2)
        self.mapper.addMapping(self.lineEditFamilyname, 3)
        self.mapper.addMapping(self.lineEditEGNEIK, 4)
        self.mapper.addMapping(self.lineEditPhone, 5)
        self.mapper.addMapping(self.lineEditNotes, 6)
        
        relationModel = model.relationModel(0)
        mapperAdr = QtGui.QDataWidgetMapper(self)
        
        mapperAdr.setModel(relationModel)
        mapperAdr.setItemDelegate(QtSql.QSqlRelationalDelegate(self))
        mapperAdr.addMapping(self.lineEditAdrStreet, 0)
        self.mapper.toLast()
        clid = self.mapper.currentIndex()
        self.loadAddress(clientsDict[clid].address)
        
    #----------------------------------------------------------------------
    def clearClients(self):
        """Clear all fields in the clients' tab"""
        
        self.lineEditName.clear()
        self.lineEditSurname.clear()
        self.lineEditFamilyname.clear()
        self.lineEditEGNEIK.clear()
        self.lineEditPhone.clear()
        self.lineEditNotes.clear()
        
        self.lineEditAdrStreet.clear()
        self.lineEditAdrStreetNomer.clear()
        self.lineEditAdrEntr.clear()
        self.lineEditAdrBlock.clear()
        self.lineEditAdrFloor.clear()
        self.lineEditAdrApp.clear()
        self.lineEditAdrTown.clear()
        self.lineEditAdrPostCode.clear()
        self.lineEditAdrCountry.clear()
        
        self.lineEditTrfSfKg.clear()
        self.lineEditTrfSfCeni.clear()
        
        self.pushButtonSaveClient.setEnabled(False)
    
    def loadClientsData(self):
        """
        test client
        """
        
        aclient = clientsDict[1]
        self.loadClient(aclient)
        self.loadAddress(aclient.address)
        self.loadTarifa(aclient.tarifa)
        
    def loadClient(self, client):
        self.lineEditName.setText(client.ime)
        self.lineEditSurname.setText(client.prezime)
        self.lineEditFamilyname.setText(client.familia)
        self.lineEditEGNEIK.setText(client.egneik)
        self.lineEditPhone.setText(client.telefon)
        self.lineEditNotes.setText(client.notes)
        
    def getClient(self):
        ime = self.lineEditName.text()
        prezime = self.lineEditSurname.text()
        familia = self.lineEditFamilyname.text()
        egneik = self.lineEditEGNEIK.text()
        telefon = self.lineEditPhone.text()
        notes = self.lineEditNotes.text()
        
        client = Client('', ime, prezime, familia, egneik, telefon, notes)
        client.address = self.getAddress()
        client.tarifa = self.getTarifa()
        
        return client
        
    def loadAddress(self, address):
        ## street, postcode, streetNomer, block, vhod, appartment, floor, country="BULGARIA", town="София"
        self.lineEditAdrStreet.setText(address.street)
        self.lineEditAdrStreetNomer.setText(address.streetNomer)
        self.lineEditAdrEntr.setText(address.vhod)
        self.lineEditAdrBlock.setText(address.block)
        self.lineEditAdrFloor.setText(address.floor)
        self.lineEditAdrApp.setText(address.appartment)
        self.lineEditAdrTown.setText(address.town)
        self.lineEditAdrPostCode.setText(address.postcode)
        self.lineEditAdrCountry.setText(address.country)
        
    def getAddress(self):
        street = self.lineEditAdrStreet.text()
        streetNomer = self.lineEditAdrStreetNomer.text()
        vhod = self.lineEditAdrEntr.text()
        block = self.lineEditAdrBlock.text()
        floor = self.lineEditAdrFloor.text()
        appartment = self.lineEditAdrApp.text()
        town = self.lineEditAdrTown.text()
        postcode = self.lineEditAdrPostCode.text()
        country = self.lineEditAdrCountry.text()
        
        adres = Address(street, postcode, streetNomer, block, vhod, appartment, floor, country, town)
        
        return adres
        
    def loadTarifa(self, tarifa):
        kila = QtCore.QString(str(tarifa.kilaSf))
        ceni = QtCore.QString(str(tarifa.ceniSfStandard))
        self.lineEditTrfSfKg.setText(kila)
        self.lineEditTrfSfCeni.setText(ceni)
        
    def getTarifa(self):
        kila = self.lineEditTrfSfKg.text()
        ceni = self.lineEditTrfSfCeni.text()
        
        newKila = list(kila.split(','))
        print newKila
    
    #----------------------------------------------------------------------
    def on_lineEditName_textChanged(self):
        """"""
        self.pushButtonSaveClient.setEnabled(True)
        
    #----------------------------------------------------------------------
    @QtCore.pyqtSlot()    
    def on_pushButtonNewClient_clicked(self):
        self.initClients()
     
    @QtCore.pyqtSlot() 
    def on_pushButtonSaveClient_clicked(self):
        newClient = self.getClient()
        print newClient
        ok = bz.insertClientInDBase(newClient)
        if ok:
            QtGui.QMessageBox.information(self, "Success", "Client Successfully Inserted in DB")
        else:
            QtGui.QMessageBox.warning(self, "KUR", "Error Inserting Client's Data.")
        
    @QtCore.pyqtSlot()    
    def on_pushButtonLoadClient_clicked(self):
        ## self.loadClientsData()
        self.mapper.toNext()
      
    ################################### END OF CLIENTS' TAB #####################################
        
    @QtCore.pyqtSlot()
    def on_lineEditSenderName_returnPressed(self):
        clid, ok = self.lineEditSenderName.text()[-2:].toUInt()
        if ok:
            if clid not in clientsDict:
                ## popup dialog for enter client
                QtGui.QMessageBox.warning(self, "Missing Client", "This name is not in the dbase!")
            else:
                self.sender = clientsDict[clid]            
        self.updateAll()
        
    @QtCore.pyqtSlot()
    def on_pushButtonShowSender_clicked(self):
        if self.sender:
            QtGui.QMessageBox.information(self, "Client Details", self.sender.toString())
        else:
            QtGui.QMessageBox.warning(self, "Missing Client", "First - enter a Client, then ask for details!")
        
    @QtCore.pyqtSlot()
    def on_lineEditReceiverName_returnPressed(self):
        clid, ok = self.lineEditSenderName.text()[-2:].toUInt()
        if ok:
            if clid not in clientsDict:
                ## popup dialog for enter client
                QtGui.QMessageBox.information(self, "Missing Client", "This name is not in the dbase!")
            else:
                self.receiver = clientsDict[clid]
        self.updateAll()
            
    ## if we have Custom address - set and update
    @QtCore.pyqtSlot()
    def on_lineEditReceiverTown_editingFinished(self):
        self.updateAll()
        
    @QtCore.pyqtSlot()
    def on_lineEditReceiverTown_returnPressed(self):
        self.lineEditReceiverTown.selectAll()
        
    @QtCore.pyqtSlot()
    def on_pushButtonShowReceiver_clicked(self):
        if self.receiver:
            QtGui.QMessageBox.information(self, "Client Details", self.receiver.toString())
        else:
            QtGui.QMessageBox.warning(self, "Missing Client", "First - enter a Client, then ask for details!")
    
    ## Actions (main menu actions) #########################################################################
    @QtCore.pyqtSlot()
    def on_actionNew_triggered(self):
        self.init()
   
    def on_actionPrint_preview_triggered(self):
        tov = self.createTov()
        self.preview = QPrintPreviewDialog()
        self.connect(self.preview, SIGNAL("paintRequested (QPrinter *)"), SLOT("print (QPrinter *)"))
        self.connect(self, SIGNAL("loadFinished (bool)"), self.execpreview)
        def execpreview(self, arg):
                print arg
                self.preview.exec_()

        
    def on_actionPrint_triggered(self):
        pass
        
    
    @QtCore.pyqtSlot()
    def on_actionAbout_triggered(self):
        splash_pix = QtGui.QPixmap(':/images/zlabssplash.png')
        icon = QtGui.QIcon(splash_pix)
        widget = QtGui.QWidget(self)
        widget.setWindowIcon(icon)
        QtGui.QMessageBox.about(widget, QtCore.QString("About This Product"),
                QtCore.QString("version %L1. <BR> Designed by <a href=\"http://zombium.org\">zombium.labs</a>.").arg(__version__))
    
    @QtCore.pyqtSlot()
    def on_actionAbout_Qt_triggered(self):
        QtGui.QMessageBox.aboutQt(self)
    
    ## Buttons clicked
    @QtCore.pyqtSlot()
    def on_pushButtonClearAll_clicked(self):
        self.init()
        
    @QtCore.pyqtSlot()
    def on_pushButtonInsert_clicked(self):
        currentTov = self.createTov()
        ok = bz.insertTovInDBase(currentTov)
        if ok:
            QtGui.QMessageBox.information(self, "Tov Inser", "Insert in DB successfull.")
            #self.tovPrintDocument = TovPlainDoc(currentTov)
            self.actionPrint.setEnabled(True)
            self.tovWithModel()
            
        else:
            QtGui.QMessageBox.warning(self, "Shit", "Error in insert in DB.")

    @QtCore.pyqtSlot()
    def on_pushButtonUpdateTime_clicked(self):
        self.setTimee()
        
    @QtCore.pyqtSlot()
    def on_pushButtonServiceSpeed_clicked(self):
        if self.currentSpeedIndex >= len(self.speed)-1:
            self.currentSpeedIndex = 0
        else:
            self.currentSpeedIndex += 1
        self.pushButtonServiceSpeed.setText(self.speed[self.currentSpeedIndex])
        self.updateAll()
    
    ### FINANCIALS ######################################
            
    def updateAll(self):
        
        ## update RECEIVER details
        if self.receiver:
            self.lineEditReceiverPhone.setText(self.receiver.telefon)
            self.lineEditReceiverName.setText(self.receiver.getFullName())
            self.lineEditReceiverAddress.setText(self.receiver.address.getAddress())
            self.lineEditReceiverPhone.setText(self.receiver.telefon)
            self.lineEditReceiverTown.setText(self.receiver.address.town)
            
            ## if self.lineEditReceiverTown.text().toLower() == unicode('софия', 'Utf8'):
            if self.receiver.address.town.lower().strip() == unicode('софия', 'Utf8'):
                self.destination = 'sofia'
            else:
                self.destination = 'countryside'
            if self.atAccountOf == 'receiver':
                self.courierFee = self.calculateCourierFee(self.receiver.tarifa)
            
        ## update SENDER details
        if self.sender:
            self.lineEditSenderPhone.setText(self.sender.telefon)
            self.lineEditSenderName.setText(self.sender.getFullName())
            self.lineEditSenderAddress.setText(self.sender.address.getAddress())
            self.lineEditSenderPhone.setText(self.sender.telefon)
            self.lineEditSenderTown.setText(self.sender.address.town)
            if self.atAccountOf == 'sender':
                self.courierFee = self.calculateCourierFee(self.sender.tarifa)
                        
        self.nalojenPlatejFee = self.nalojenPlatejValue*(defaults['nalojenPlatejRate']/100.0)
        self.courierFeeInclVat = self.courierFee*(1+defaults['vatTaxRate']/100.0)
        self.insuranceFee = self.insuranceValue*(defaults['insuranceRate']/100.0)
        
        ## fill corresponding gui fields
        self.lineEditPackWeght.setText("%g" % self.packWeight)
        self.lineEditPackCount.setText("%g" % self.packCount)
        self.lineEditNalojenPlatejValue.setText("%g" % self.nalojenPlatejValue)
        self.lineEditNalojenPlatejFee.setText("%g" % self.nalojenPlatejFee)
            
        if self.checkBoxFixedTime.isChecked():
            self.lineEditFixedTimeFee.setEnabled(True)
            self.fixedTimeFee = defaults['fixedTimeRate']
            self.lineEditFixedTimeFee.setText("%g" % self.fixedTimeFee)
            
        else:
            self.lineEditFixedTimeFee.clear()
            self.lineEditFixedTimeFee.setEnabled(False)
            
        if self.insuranceFee:
            self.lineEditInsuranceFee.setEnabled(True)
            self.lineEditInsuranceFee.setText("%g" % self.insuranceFee)
        else:
            self.lineEditInsuranceFee.clear()
            self.lineEditInsuranceFee.setEnabled(False)
        
        self.lineEditCourierFee.setText("%g" % self.courierFee)
        self.lineEditCourierFeeInclVat.setText("%g" % self.courierFeeInclVat)
        self.lineEditTotal.setText("%g" % self.calculateTotal())
            
    ## TOTAL
    def calculateTotal(self):
        total = self.nalojenPlatejValue + self.nalojenPlatejFee + self.courierFeeInclVat + self.insuranceFee +\
              self.obrDocsFee + self.obrRazpiskaFee + self.onDemandFee
        if self.checkBoxFixedTime.isChecked():
            total += self.fixedTimeFee
        if self.checkBoxInsurance.isChecked():
            total += self.insuranceFee
            
        return total

    def calculateCourierFee(self, tarifa):
        import math
        kila = sorted(tarifa.td[self.destination][self.currentSpeedIndex].keys())
        if 0< self.packWeight <= kila[0]:
            return tarifa.td[self.destination][self.currentSpeedIndex][kila[0]]
        elif self.packWeight > kila[-1]:
            extra = (math.ceil(self.packWeight - kila[-1])*tarifa.extraKG[self.destination])        
            return tarifa.td[self.destination][self.currentSpeedIndex][kila[-1]] + extra
        else:
            for i in range(0, len(kila)):            
                if kila[i] < self.packWeight <= kila[i+1]:
                    return tarifa.td[self.destination][self.currentSpeedIndex][kila[i+1]]
                
            
    ## Clear Button
    @QtCore.pyqtSlot()
    def on_pushButtonClearFinancials_clicked(self):
        self.initFinancials()
    
    ## Update Button
    @QtCore.pyqtSlot()
    def on_pushButtonUpdateFinancials_clicked(self):
        self.updateAll()
    
    ## Weght
    @QtCore.pyqtSlot()
    def on_lineEditPackWeght_editingFinished(self):
        weight, ok = self.lineEditPackWeght.text().toFloat()
        if ok:
            self.packWeight = weight
        self.updateAll()

    @QtCore.pyqtSlot()
    def on_lineEditPackWeght_returnPressed(self):
        self.lineEditPackWeght.selectAll()

    ## Pack Count
    @QtCore.pyqtSlot()
    def on_lineEditPackCount_editingFinished(self):
        count, ok = self.lineEditPackCount.text().toFloat()
        if ok:
            self.packCount = count
        self.updateAll()

    @QtCore.pyqtSlot()
    def on_lineEditPackCount_returnPressed(self):
        self.lineEditPackCount.selectAll()

    ## Nalojen Platej
    @QtCore.pyqtSlot()
    def on_lineEditNalojenPlatejValue_editingFinished(self):
        np, ok = self.lineEditNalojenPlatejValue.text().toFloat()
        if ok:
            self.nalojenPlatejValue = np
        self.updateAll()

    @QtCore.pyqtSlot()
    def on_lineEditNalojenPlatejValue_returnPressed(self):
        self.lineEditNalojenPlatejValue.selectAll()

    ## Courier Fee
    @QtCore.pyqtSlot()
    def on_lineEditCourierFee_editingFinished(self):
        cf, ok = self.lineEditCourierFee.text().toFloat()
        if ok:            
            self.courierFee = cf
        self.updateAll()

    @QtCore.pyqtSlot()
    def on_lineEditCourierFee_returnPressed(self):
        self.lineEditCourierFee.selectAll()
        
    ## Insurance Fee
    @QtCore.pyqtSlot()
    def on_lineEditInsuranceValue_editingFinished(self):
        ins, ok = self.lineEditInsuranceValue.text().toFloat()
        if ok:            
            self.insuranceValue = ins
        self.updateAll()

    @QtCore.pyqtSlot()
    def on_lineEditInsuranceValue_returnPressed(self):
        self.lineEditInsuranceValue.selectAll()

    ## Fixed Time Fee
    ##@QtCore.pyqtSlot()
    def on_checkBoxFixedTime_stateChanged(self):
        self.updateAll()
   
    def on_checkBoxInsurance_stateChanged(self):
        if self.checkBoxInsurance.isChecked():
            self.lineEditInsuranceValue.setEnabled(True)
            self.updateAll()
        else:
            self.lineEditInsuranceValue.clear()
            self.lineEditInsuranceValue.setEnabled(False)
            self.lineEditInsuranceFee.clear()
            self.lineEditInsuranceFee.setEnabled(False)
            self.insuranceFee = 0.0
            self.updateAll()
          
    def on_checkBoxBackDocs_stateChanged(self):
        if self.checkBoxBackDocs.isChecked():
            self.obrDocsFee = defaults['obrDocs']
            self.updateAll()
        else:
            self.obrDocsFee = 0.0
            self.updateAll()
            
    def on_checkBoxBackRasp_stateChanged(self):
        if self.checkBoxBackRasp.isChecked():
            self.obrRazpiskaFee = defaults['obrRazpiska']
            self.updateAll()
        else:
            self.obrRazpiskaFee = 0.0
            self.updateAll()
            
    def on_checkBoxOnDemand_stateChanged(self):
        if self.checkBoxOnDemand.isChecked():
            self.onDemandFee = defaults['onDemand']
            self.updateAll()
        else:
            self.onDemandFee = 0.0
            self.updateAll()
            
        
    ## At Account Of Sender
    @QtCore.pyqtSlot()
    def on_radioButtonSender_clicked(self):
        self.atAccountOf = 'sender'
        self.updateAll()
        
    ## At Account Of Receiver
    @QtCore.pyqtSlot()
    def on_radioButtonReceiver_clicked(self):
        self.atAccountOf = 'receiver'
        self.updateAll()

    

if __name__ == '__main__':
    
    # Create and display the splash screen
    splash_pix = QtGui.QPixmap(':/images/zlabssplash.png')
    splash = QtGui.QSplashScreen(splash_pix, QtCore.Qt.WindowStaysOnTopHint)
    splash.setMask(splash_pix.mask())
    splash.show()
    splash.showMessage("Initialize Data Base ...", QtCore.Qt.AlignHCenter|QtCore.Qt.AlignBottom, QtCore.Qt.white)
    app.processEvents()
    
    bz = DB()
    
    splash.showMessage("Loading clients data ...", QtCore.Qt.AlignHCenter|QtCore.Qt.AlignBottom, QtCore.Qt.white)
    app.processEvents()
    
    clientsList, clientsDict = bz.getClients()
    
    splash.showMessage("Loading default config data ...", QtCore.Qt.AlignHCenter|QtCore.Qt.AlignBottom, QtCore.Qt.white)
    app.processEvents()
    
    defaults = bz.getDefaultConfig()
    
    splash.showMessage("Ready.", QtCore.Qt.AlignHCenter|QtCore.Qt.AlignBottom, QtCore.Qt.white)
    app.processEvents()   
    
    form = DemoImpl()
    form.show()
    splash.finish(form)
    sys.exit(app.exec_())
